<?php
/**
 *
 * @authors xiadx (xiadx@zpdchina.com)
 * @date    2017-02-24 11:56:24
 * @version $Id$
 */

class IndexController extends Yaf_Controller_Abstract {

    public function insertAction()
    {

    }

    public function indexAction()
    {
        echo '恭喜，successfully!';exit;
/*        if ($exception->getCode() == 516 && !headers_sent())
        {
            header('HTTP/1.1 404 Not Found', TRUE, 404);
            header('status: 404 Not Found', TRUE, 404);
//            exit();
            return FALSE;
        }*/
        // $html = Kohana_Exception::handler($exception);


        // echo '111';exit;
        // $post = $this->getRequest();
        $post = $_REQUEST;
        $user_department = $post['user_department'];
        $user_department_id = $post['user_department_id'];

        $modify_time = $post['modify_time'];

        $jsonData = isset($post['data']) ? $post['data'] : [];
        // 解压缩数据
        $jsonData = Utility::uncompress($jsonData,$post["compression_http_data"]);

        /*$query = DB::select()->from('zhuyuan_yizhu_changqi')->where('zhuyuan_id', '=', '369139')->execute();*/
        /*$query = DB::query(Database::SELECT, "SELECT * FROM zhuyuan_yizhu_changqi WHERE zhuyuan_id = '369139'")->execute();*/

        $chaxun_changqi_where = '';
        $chaxun_linshi_where = '';

        if(!empty($user_department_id)){
            $chaxun_changqi_where .= " AND t.zhuyuan_id = '$user_department_id'";
            $chaxun_linshi_where .= " AND t.zhuyuan_id = '$user_department_id'";
        }

        if($user_department){
            $chaxun_changqi_where .= " AND t.zhuyuan_bingqu = '$user_department'";
            $chaxun_linshi_where.= " AND t.zhuyuan_bingqu = '$user_department'";
        }

        if($modify_time){
            $chaxun_changqi_where .= " AND a.modify_time >= '$modify_time'";
            $chaxun_linshi_where.= " AND a.modify_time = '$modify_time'";
        }

        if(!empty( $jsonData)){
            $data = json_decode($jsonData,true);
            $chaxun_changqi_where .= " AND a.zuhao NOT IN ('".implode("','", $data) . '\')';
            $chaxun_linshi_where .= " AND a.zuhao NOT IN ('".implode("','", $data) . '\')';
        }


        $huanzhe_where = " t.zhuangtai = '住院中' ";
        $huanzhe_chuyuan_baoliu_shijian = ["value"=>"6",
            "unit"=>"HOUR"];

        if($huanzhe_chuyuan_baoliu_shijian){
            $huanzhe_where = " (t.zhuangtai = '住院中' or (t.zhuangtai = '已出院' and ".Utility::getIntervalSqlString("t.chuyuan_riqi_time",$huanzhe_chuyuan_baoliu_shijian).")) ";
        }

        /*长期*/
        $time = intval (date("Hi"));
        $show_new_yizhu = "0000";
        if($time >= intval($show_new_yizhu)){
            $changqi_str = '';
            $interval = ["value"=>"6","unit"=>"HOUR"];
            $str = Utility::getIntervalSqlString("a.stop_time",$interval);
            $changqi_str_ing = " AND a.state = '开始执行'";
            $changqi_str = " AND (a.state='停止执行' AND ".$str;
            /*if(C('changqi_start_end_time_diff_no_need')){
                $chaxun_changqi['_string'] .= "(UNIX_TIMESTAMP(a.stop_time) - UNIX_TIMESTAMP(a.start_time))>=".C('changqi_start_end_time_diff_no_need');
            }*/
            $changqi_str .= ")";
            // 开始执行
            $chaxun_changqi_where_ing = $chaxun_changqi_where . $changqi_str_ing;
            // 停止执行
            $chaxun_changqi_where_stop = $chaxun_changqi_where . $changqi_str;

            //医嘱表增加相应dx2016-07-12增加返回字段chushi_state
            $filed_str_changqi = "a.id,a.zhuyuan_id,'长期' type,a.content,a.start_time,a.stop_time,a.yongfa,a.yongfa_type,a.ciliang,a.shiyong_danwei,a.pinlv,a.zuhao,a.zhixing_state,a.yizhu_yongfa_type,a.meiri_cishu,a.wancheng_cishu,a.beizhu,a.xiangying_state,a.state,a.chushi_state,a.modify_time,a.shouci_yongyao,a.yongyao_time";
            // 长期的开始执行医嘱 SQL
            $sql_ing = "SELECT $filed_str_changqi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_changqi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $huanzhe_where $chaxun_changqi_where_ing ";
            // 长期的停止执行医嘱的sql
            $sql_stop = "SELECT $filed_str_changqi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_changqi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $huanzhe_where $chaxun_changqi_where_stop ";
        }

        // 长期的开始执行
        $zhuyuan_yizhu_changqi_data_ing = DB::query(Database::SELECT, $sql_ing)->execute()->as_array();
        // 长期的停止执行
        $zhuyuan_yizhu_changqi_data_stop = DB::query(Database::SELECT, $sql_stop)->execute()->as_array();

        // $zhuyuan_yizhu_changqi_data_stop = [];
        $zhuyuan_yizhu_changqi_data = $zhuyuan_yizhu_changqi_data_ing + $zhuyuan_yizhu_changqi_data_stop;
        /*end*/
        // print_r($zhuyuan_yizhu_changqi_data_ing);exit;
        /*临时医嘱*/
        $zhuyuan_yizhu_linshi_data = [];
        $show_linshi_24_hour = true;//临时医嘱24小时显示
        $interval = array(
            "value"=>"24",
            "unit"=>"HOUR",
        );
        $linshi_str = Utility::getIntervalSqlString("a.xiada_time",$interval);
        if($show_linshi_24_hour == true){
            $chaxun_linshi_where .= ' AND ' . $linshi_str;
            $chaxun_linshi_where .= " AND a.state in('开始执行','停止执行')";
        } else {
            $stop_linshi_interval = ["value"=>"8", "unit"=>"HOUR"];
            $stop_linshi_str = Utility::getIntervalSqlString('a.xiada_time' , $stop_linshi_interval);
            /*是否开启停止执行临时医嘱 开关*/
            /*是否开启 停止执行临时医嘱
                on:开启
                off:关闭
            */
            $state_of_stop_linshi = 'on';
            // 停止执行的临时医嘱配置
            if($state_of_stop_linshi == 'on'){
                $chaxun_linshi_where .= " (a.state = '开始执行' and $linshi_str) or (a.state = '停止执行' and $stop_linshi_str )";
            }else{
                $chaxun_linshi_where .= " a.state = '开始执行' and $linshi_str ";
            }
            /*end*/
        }
        $filed_str_linshi = "a.id,a.zhuyuan_id,'临时' type,a.content,a.xiada_time as start_time,a.zhixing_time as stop_time,a.yongfa,a.yongfa_type,a.ciliang,a.shiyong_danwei,a.pinlv,a.zuhao,a.zhixing_state,a.yizhu_yongfa_type,a.meiri_cishu,a.wancheng_cishu,a.beizhu,a.xiangying_state,a.state,a.chushi_state,a.modify_time,a.shouci_yongyao,a.yongyao_time";
        $sql = "SELECT $filed_str_linshi FROM zhuyuan_basic_info as t LEFT JOIN zhuyuan_yizhu_linshi AS a ON t.zhuyuan_id=a.zhuyuan_id WHERE $huanzhe_where $chaxun_linshi_where ";
        $zhuyuan_yizhu_linshi_data = DB::query(Database::SELECT, $sql)->execute()->as_array();
        // $zhuyuan_yizhu_linshi_data = [];
        $yizhu_data = array();
        $yizhu_data = $zhuyuan_yizhu_changqi_data + $zhuyuan_yizhu_linshi_data;

        $async_result = array();
        $tiaoshu = 100;
        $now = date("y-m-d h:i:s", time());
        $today_date = date('Y-m-d');
        $today = strtotime($today_date);//获取前十位
        if($yizhu_data){
            //查询组号
            $zuhao_chaxun = array();
            $zuhao_str = "";
            foreach($yizhu_data as $k=>$v){
                $zuhao_chaxun[$v['zuhao']] = $v['zuhao'];
            }
            //查询当前最大完成次数
            $where_str = ' zhixing_zuhao IN (\'' . implode("','", $zuhao_chaxun) . '\')';
            $where_str .= " AND zhixing_state = '执行完毕'";
            // $where_str .= " AND case when type ='临时' then  1=1 else yizhu_time = '".$today_date."' end";
            $where_str_linshi = " AND `type`='临时' ";

            /*临时当前最大完成次数*/
            $sql_linshi = "SELECT zhixing_zuhao,max(dangqian_cishu) as wancheng_cishu FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_linshi GROUP BY zhixing_zuhao";
            $zuhao_dangqian_cishu_ls = DB::query(Database::SELECT, $sql_linshi)->execute()->as_array();
            /*end*/
            /*长期当前最大完成次数*/
            $where_str_changqi = " AND `type`='长期' AND yizhu_time='$today_date' ";
            $sql_changqi = "SELECT zhixing_zuhao,max(dangqian_cishu) as wancheng_cishu FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_changqi GROUP BY zhixing_zuhao";
            $zuhao_dangqian_cishu_cq = DB::query(Database::SELECT, $sql_changqi)->execute()->as_array();
            /*end*/
            $zuhao_dangqian_cishu_cq = [];
            $zuhao_dangqian_cishu = $zuhao_dangqian_cishu_ls + $zuhao_dangqian_cishu_cq;
            //查询最后一条操作记录的状态
            $order_by = " ORDER BY zhixing_zuhao ASC,dangqian_cishu ASC,case when zhixing_state = '待配液' or zhixing_state = '已配液' then 1
            when zhixing_state = '已校对' then 2 when zhixing_state = '开始执行' or zhixing_state = '暂停执行' then 3 when zhixing_state = '执行完毕' then 4 end ASC ,real_time ASC";
            /*临时*/
            $sql_1_ls = "SELECT zhixing_zuhao,zhixing_state FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_linshi $order_by";
            $zuhao_last_state_ls = DB::query(Database::SELECT, $sql_1_ls)->execute()->as_array();
            /*end*/
            /*长期*/
            $sql_1_cq = "SELECT zhixing_zuhao,zhixing_state FROM zhuyuan_yizhu_zhixing_history WHERE $where_str $where_str_changqi $order_by";
            $zuhao_last_state_cq = DB::query(Database::SELECT, $sql_1_cq)->execute()->as_array();
            /*end*/
            // $zuhao_last_state_cq = [];
            $zuhao_last_state = $zuhao_last_state_ls + $zuhao_last_state_cq;

            foreach($yizhu_data as $key => $one_yizhu_info){
                $zuhao = $one_yizhu_info['zuhao'];
                //完成次数
                $wancheng_cishu = isset($zuhao_dangqian_cishu[$zuhao]) ? $zuhao_dangqian_cishu[$zuhao] : 0;
                $kuatian = isset($zuhao_last_state[$zuhao]) ? "否" : "是";
                $history_lishi_zhuangtai = isset($zuhao_last_state[$zuhao]) ? $zuhao_last_state[$zuhao] : $one_yizhu_info['chushi_state'];
                if($history_lishi_zhuangtai == "执行完毕"){
                    $history_lishi_zhuangtai = $one_yizhu_info['chushi_state'];
                }

                $yongfa_type = $one_yizhu_info['yizhu_yongfa_type'];
                $zhixing_cishu['daily_need_number'] = $one_yizhu_info['meiri_cishu'];
                $zhixing_cishu['daily_finish_number'] = $wancheng_cishu;
                /*//特殊处理
                if(C('hospital_name') == "张家港市第一人民医院"){
                    if($yongfa_type == "注射"){
                        $yongfa_type = "输液";
                    }
                }
                //祥云读取备注新表，待优化
                if(C('get_barcode_from_new_table')){
                    $one_yizhu_info['beizhu'] = $this->getBeizhu($one_yizhu_info['zuhao']);
                }*/

                if($one_yizhu_info["type"] == "长期"){
                    $temp_yizhu_id = '100'.$one_yizhu_info["id"];
                }else{
                    $temp_yizhu_id = '200'.$one_yizhu_info["id"];
                }

                /*特殊字符转义*/
                /*if (get_magic_quotes_gpc()){
                    $one_yizhu_info["content"] = $one_yizhu_info["content"];
                }else{
                    $one_yizhu_info["content"] = addslashes($one_yizhu_info["content"]);
                }*/

                //sql拼装
                $i = intval($key/$tiaoshu);
                // $i = 1;
                //每组第几个
                $arr_zer = $key%$tiaoshu;
                if($arr_zer == 0)
                {
                    $async_result[$i] = "REPLACE INTO yizhu_info (yizhu_id,zhuyuan_id,yizhu_type,content,start_time,stop_time,yongfa,yongliang,shiyong_danwei,pinlv,zuhao,zhixing_state,meiri_cishu,wancheng_cishu,yongfa_type,kuatian,beizhu,xiangying_state,zhuangtai,yizhu_time,chushi_state,modify_time,shouci_yongyao,yongyao_time) SELECT  '".$temp_yizhu_id."','".$one_yizhu_info["zhuyuan_id"]."','".$one_yizhu_info["type"]."','".$one_yizhu_info["content"]."','".$one_yizhu_info["start_time"]."','".$one_yizhu_info["stop_time"]."','".$one_yizhu_info["yongfa"]."','".$one_yizhu_info["ciliang"]."','".$one_yizhu_info["shiyong_danwei"]."','".$one_yizhu_info["pinlv"]."','".$one_yizhu_info["zuhao"]."','".$history_lishi_zhuangtai."','".$zhixing_cishu['daily_need_number']."','".$zhixing_cishu['daily_finish_number']."','".$yongfa_type."','".$kuatian."','".$one_yizhu_info["beizhu"]."','".$one_yizhu_info["xiangying_state"]."','".$one_yizhu_info["state"]."','".$today_date."','".$one_yizhu_info["chushi_state"]."','".$one_yizhu_info["modify_time"]."','".$one_yizhu_info["shouci_yongyao"]."','".$one_yizhu_info["yongyao_time"]."'";
                }
                else
                {
                    $async_result[$i] .= " union all SELECT '".$temp_yizhu_id."','".$one_yizhu_info["zhuyuan_id"]."','".$one_yizhu_info["type"]."','".$one_yizhu_info["content"]."','".$one_yizhu_info["start_time"]."','".$one_yizhu_info["stop_time"]."','".$one_yizhu_info["yongfa"]."','".$one_yizhu_info["ciliang"]."','".$one_yizhu_info["shiyong_danwei"]."','".$one_yizhu_info["pinlv"]."','".$one_yizhu_info["zuhao"]."','".$history_lishi_zhuangtai."','".$zhixing_cishu['daily_need_number']."','".$zhixing_cishu['daily_finish_number']."','".$yongfa_type."','".$kuatian."','".$one_yizhu_info["beizhu"]."','".$one_yizhu_info["xiangying_state"]."','".$one_yizhu_info["state"]."','".$today_date."','".$one_yizhu_info["chushi_state"]."','".$one_yizhu_info["modify_time"]."','".$one_yizhu_info["shouci_yongyao"]."','".$one_yizhu_info["yongyao_time"]."'";
                }
            }
        }
        $json_encode = json_encode(['update_sql' => $async_result]);
        $ret = Utility::compress($json_encode,$post["compression_http_data"]);
        echo $ret;
        exit;

//		$this->getView()->assign("exception", $exception);
    }
}
